package com.mankind.ssm.controller;

import com.mankind.ssm.common.CONSTANT;
import com.mankind.ssm.common.Page;
import com.mankind.ssm.common.util;
import com.mankind.ssm.pojo.Role;
import com.mankind.ssm.pojo.User;
import com.mankind.ssm.pojo.UserInfo;
import com.mankind.ssm.pojo.UserRole;
import com.mankind.ssm.service.*;
import com.sun.org.apache.xpath.internal.SourceTree;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mankind on 2017/7/10.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //service类
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionSerivce;
//    @RequestMapping("/login")
//    public ModelAndView login(HttpServletRequest request, User user){
//        ModelAndView modelAndView = new ModelAndView();
//        System.out.println(user.getUserAccount()+" "+user.getUserPassword());
//        //方法绑定绑定参数
//        Integer userId=userService.loginCheck(user);
//        //如果验证失败,返回登录失败页面
//        System.out.println("登录验证ID："+userId);
//        if(userId==null){
//            modelAndView.setViewName("loginError");
//        }
//        //如果验证通过,进入个人主页
//        else{
//               //修改登录时间
//               UserInfo userInfo=userInfoService.getUserInfoById(userId);
//               userInfo.setRecentlyTime(new Date());
//               userInfoService.update(userInfo);
//                //进入主页前验证身份
//               boolean check= userRoleService.managerCheck(userId);
//
//               //管理员身份验证通过
//               if(check==true){
//                   modelAndView.setViewName("manager");
//               }else{
//                   modelAndView.setViewName("home");
//               }
//                HttpSession session=request.getSession();
//                session.setAttribute("userId",userId);
//        }
//        return modelAndView;
//    }
    @RequestMapping("/login2")
    public String login2(User user){
        //user.setUserPassword();
        user.setUserPassword(util.encBase64(user.getUserPassword()));
        UsernamePasswordToken token =new UsernamePasswordToken(user.getUserAccount(), user.getUserPassword());
        Subject currentUser = SecurityUtils.getSubject();
        try {
            if (!currentUser.isAuthenticated()){
                currentUser.login(token);
            }
            return "manager";
        } catch (Exception e) {
            return "redirect:/index.jsp";
        }
    }
    @RequestMapping("/role")
    public String goToRoleJsp(Model model){
        model.addAttribute("permissionList", permissionSerivce.selectAllPermission());
        return "role";
    }
    @RequestMapping("/permission")
    public String goToPermissionJsp(){
        return "permission";
    }
    @RequestMapping("/manager")
    public String goToManagerJsp(){
        return "manager";
    }
//    @RequestMapping("/register")
//    public ModelAndView register(HttpServletRequest request){
//        ModelAndView modelAndView = new ModelAndView();
//        String userAccount=request.getParameter("userAccount");
//        String userPassword=request.getParameter("userPassword");
//        String userName=request.getParameter("userName");
//        User user=new User(userAccount,userPassword);
//        Integer userId=userService.register(user);
//        //返回userId表明注册成功
//        if(userId!=null){
//            modelAndView.setViewName("userInfo");
//            HttpSession session=request.getSession();
//            session.setAttribute("userId",userId);
//            request.setAttribute("userName",userName);
//        }else{
//            modelAndView.setViewName("userError");
//        }
//       return modelAndView;
//    }
    @ResponseBody
    @RequestMapping(value="/createUser",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void createUser(HttpServletRequest request){
        String userName=request.getParameter("userName");
        String userAccount=request.getParameter("userAccount");
        String passWord=request.getParameter("userPassword");
        String sex=request.getParameter("sex");
        String job=request.getParameter("job");
        String wechat=request.getParameter("wechat");
        String email=request.getParameter("email");
        String userBirthday=request.getParameter("userBirthday");
        String telephone=request.getParameter("telephone");
        User user=new User(userAccount,passWord);
        Integer userId=userService.register(user);
        //返回userId表明注册成功
        Date date=null;
        if(userId!=null){
            if(userBirthday!=""){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    date = sdf.parse(userBirthday);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            UserInfo userInfo=new UserInfo();
            userInfo.setRecentlyTime(new Date());
            userInfo.setUserId(userId);
            userInfo.setEmail(email);
            userInfo.setJob(job);
            userInfo.setSex(sex);
            userInfo.setUserBirthday(date);
            userInfo.setTelephone(telephone);
            userInfo.setUserName(userName);
            userInfo.setWechat(wechat);
            userInfo.setUpdateTime(new Date());
            System.out.println(userInfo);
            userService.registerDetail(userInfo);
        }else{
            System.out.println("注册失败!!!");
        }
    }
    @ResponseBody
    @RequestMapping(value="/accountCheck",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map AccountExistCheck(HttpServletRequest request){
        Map<String,Object> json=new HashMap<String, Object>();
        String account=request.getParameter("userAccount");
        boolean isExist=userService.existJudge(account);
        //如果存在则说明不能被注册,如果不存在才能注册
        json.put("valid",!isExist);
        return json;
    }
//    @RequestMapping("/register_detail")
//    public ModelAndView reigster_detail(HttpServletRequest request){
//        ModelAndView modelAndView = new ModelAndView();
//        HttpSession session=request.getSession();
//        Integer userId=(Integer)session.getAttribute("userId");
//        String IP= util.getRealIP(request);
//        String userName=request.getParameter("userName");
//        //if(userName==null) userName="";
//        String sex=request.getParameter("sex");
//        //if(sex==null) sex="";
//        String userBirthday=request.getParameter("userBirthday");
//        //if(userBirthday==null) userBirthday="";
//        String job=request.getParameter("job");
//        //if(job==null) job="";
//        String email=request.getParameter("email");
//        //if(email==null)email="";
//        String wechat=request.getParameter("wechat");
//       // if(wechat==null)email="";
//        String telephone=request.getParameter("telephone");
//        Date date = null;
//        //if(telephone==null)telephone="";
//       if(userBirthday!=null||userBirthday!=""){
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                if(userBirthday!=null){
//                    date = sdf.parse(userBirthday);
//                    System.out.println(date);
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//        }
//
//        UserInfo userInfo=new UserInfo();
//        userInfo.setRecentlyTime(new Date());
//        userInfo.setUserBirthday(date);
//        userInfo.setUserId(userId);
//        userInfo.setCurrentIp(IP);
//        userInfo.setEmail(email);
//        userInfo.setJob(job);
//        userInfo.setSex(sex);
//        userInfo.setTelephone(telephone);
//        userInfo.setUserName(userName);
//        userInfo.setWechat(wechat);
//        userInfo.setUpdateTime(new Date());
//        System.out.println(userInfo);
//        userService.registerDetail(userInfo);
//        modelAndView.setViewName("home");
//        return modelAndView;
//    }
    @ResponseBody
    @RequestMapping(value="/getUserInfoByPage",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    //public Map getUserInfoByPage(HttpServletRequest request)
    public Map getUserInfoByPage(@RequestParam(required = true, value = "Page")Integer currentPage,
                                 @RequestParam(required = false, value = "text")String text){
        Map<String,Object> json=new HashMap<String, Object>();
        Page<UserInfo> page=null;
        if(text==null||text==""){
            page=userInfoService.getUserInfoByPage(CONSTANT.USERINFO_LIST_SIZE,currentPage);
        }else{
            page= userInfoService.fuzzyQueryByPage(currentPage,CONSTANT.USERINFO_LIST_SIZE,text);
        }
        json.put("userInfoList",page.getObj());
        return json;
    }
    @ResponseBody
    @RequestMapping(value="/getUserInfoTotalPages",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map getUserInfoTotalPages(@RequestParam(required = false, value = "text")String text){
        Map<String,Object> json=new HashMap<String, Object>();
        //如果是带条件查询
        Integer totalPages=null;
        totalPages=(text==null?userInfoService.getTotalNumber():userInfoService.getTotalNumber(text));
        json.put("totalPages",totalPages);
        return json;
    }
    @ResponseBody
    @RequestMapping(value="/getUserInfoAndRoleByPage",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map getUserInfoAndRoleByPage(@RequestParam(required = true, value = "Page")Integer currentPage,
                                        @RequestParam(required = false, value = "text")String text){
        Map<String,Object> json=new HashMap<String, Object>();
        //如果是带条件查询
        Page<UserInfo> page=null;
        page=(text==null?userInfoService.getUserInfoByPage(CONSTANT.USERINFO_LIST_SIZE,currentPage):
                userInfoService.fuzzyQueryByPage(currentPage,CONSTANT.USERINFO_LIST_SIZE,text));
        int size=page.getObj().size();
        List<List<Role>> listOfList=new ArrayList<List<Role>>();
        List<Role> allRole=roleService.selectAllRole();
        allRole.remove(0);
        for(int i=0;i<size;i++){
            Integer id=page.getObj().get(i).getUserId();
            listOfList.add(userRoleService.getRoleById(id));
        }
        json.put("userInfoList",page.getObj());
        json.put("roleListOfUser",listOfList);
        json.put("allRole",allRole);
        return json;
    }
    @ResponseBody
    @RequestMapping(value="/updateUserInfo",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void updateUserInfo(HttpServletRequest request){
        Integer id=Integer.parseInt(request.getParameter("id"));
        String userName=request.getParameter("userName");
        String userAccount=request.getParameter("userAccount");
        String passWord=request.getParameter("userPassword");
        String sex=request.getParameter("sex");
        String userBirthday=request.getParameter("userBirthday");
        String job=request.getParameter("job");
        String wechat=request.getParameter("wechat");
        String email=request.getParameter("email");
        String telephone=request.getParameter("telephone");
        Date date = null;
        if(userBirthday!=""){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = sdf.parse(userBirthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        UserInfo userInfo=userInfoService.getUserInfoById(id);
        userInfo.setUserId(id);
        userInfo.setJob(job);
        userInfo.setSex(sex);
        userInfo.setUserBirthday(date);
        userInfo.setUserName(userName);
        userInfo.setTelephone(telephone);
        userInfo.setWechat(wechat);
        userInfo.setEmail(email);
        userInfo.setUpdateTime(new Date());
        userInfoService.update(userInfo);
        User user=userService.selectUserById(id);
        user.setUserPassword(passWord);//在service中添加base64加密
        userService.update(user);
    }
    @ResponseBody
    @RequestMapping(value="/deleteUserInfo",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void deleteUser(@RequestParam(required = true, value = "id")Integer id){
        userRoleService.deleteByUserId(id);
        userService.deleteById(id);
    }
    @ResponseBody
    @RequestMapping(value="/roleAssign",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void roleAssign(@RequestParam(required = true)Integer id,
                           @RequestParam(required = true)String[] roleName){
        userRoleService.assignRole(id,roleName);
        UserInfo userInfo=userInfoService.getUserInfoById(id);
        userInfo.setUpdateTime(new Date());
        userInfoService.update(userInfo);
    }
    @ResponseBody
    @RequestMapping(value="/loadUserInfo",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map loadUserInfo(@RequestParam(required = false)Integer id){
        Map<String,Object> json=new HashMap<String, Object>();
        UserInfo userInfo=userInfoService.getUserInfoById(id);
        User user=userService.selectUserById(id);
        user.setUserPassword(util.decBase64(user.getUserPassword()));
        json.put("user",user);
        json.put("userInfo",userInfo);
        return json;
    }
}